#include <my_header.h>
#include"cmdTask.h"
/*接口名称 gets_server
 *接口功能简介 用于服务端，发送指定服务器文件到本地
 *返回值的含义
 *return 0: 服务器文件发送到客户端成功
 *return -1: 文件名不匹配，下载失败
 *作者 周利通
 */
int gets(int netfd,train_t *train){
	char filename[4096] = { 0 };
	strncpy(filename, train->_data, train->_length);
	int access_ret = access(filename, F_OK);
	if (access_ret == -1) {
		return access_ret;
    }
    train->_length=strlen(filename);
    memcpy(train->_data,filename,train->_length);
    int send_filename_ret=send(netfd,&train,sizeof(train->_length)+sizeof(train->_cmdType)+train->_length,MSG_NOSIGNAL);
    ERROR_CHECK(send_filename_ret,-1,"send fliename");
    
    int fd=open(filename,O_RDWR);
    ERROR_CHECK(fd,-1,"open file");
    
    while(1){
        ssize_t read_ret=read(fd,train->_data,sizeof(train->_data));
        ERROR_CHECK(read_ret,-1,"read train.buff");
        
        train->_length=read_ret;
        if(read_ret!=1000&&read_ret!=-1){
            printf("read_ret=%lu\n",read_ret);
        }
        int send_filedata_ret=send(netfd,train,sizeof(train->_length)+sizeof(train->_cmdType)+train->_length,MSG_NOSIGNAL);
        ERROR_CHECK(send_filedata_ret,-1,"send filedata");
        
        if(read_ret==0){
            break;
        }
    }
    return 0;
}

/*接口名称 puts_server
 * 接口功能简介 用于服务端，接收上传文件到服务器
 *返回值的含义
 *return 0: 服务器文件接收成功
 *作者 周利通
 * */
int gets_client(int netfd,train_t *train)
{
	int filename_length_ret =
		recv(netfd, &train->_length, sizeof(train->_length), MSG_WAITALL);
	ERROR_CHECK(filename_length_ret, -1, "recv filename train.length");

	int filename_buff_ret =
		recv(netfd, &train->_data, sizeof(train->_data), MSG_WAITALL);
	ERROR_CHECK(filename_buff_ret, -1, "recv filename train.buff");

	char filename[4096] = { 0 };
	memcpy(filename, train->_data, train->_length);
	int fd = open(filename, O_RDWR | O_CREAT | O_TRUNC, 0666);
	ERROR_CHECK(fd, -1, "open file");

	while (1) {
		int filedata_length_ret =
			recv(netfd, &train->_length, sizeof(train->_length),
			     MSG_WAITALL);
		ERROR_CHECK(filedata_length_ret, -1,
			    "recv filedata train.length");
		if (train->_length != 1000) {
			printf("train.length=%d\n", train->_length);
		}
		if (train->_length == 0) {
			break;
		}
		int filedata_buff_ret = recv(netfd, &train->_length,
					     train->_length, MSG_WAITALL);
		ERROR_CHECK(filedata_buff_ret, -1, "recv filedata_buff_ret");

		int write_ret = write(fd, train->_data, train->_length);
		ERROR_CHECK(write_ret, -1, "write");
	}
	return 0;
}
